package it.webrules.deploymanager.core.hook;

import it.webrules.deploymanager.core.MailService;
import it.webrules.deploymanager.core.dy.ApplicationServerConnection;
import it.webrules.xsd.dmc.config.v1.Action;
import it.webrules.xsd.dmc.config.v1.Action.Waitdeployed;
import it.webrules.xsd.dmc.config.v1.Action.Waitstarted;
import it.webrules.xsd.dmc.config.v1.ExecuteCommand;
import it.webrules.xsd.dmc.config.v1.GeneralConfig;
import it.webrules.xsd.dmc.config.v1.SendEmail;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HandleHookAction {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	public void doAction(GeneralConfig generalConfig, ApplicationServerConnection serverConnection, Action actions) {

		MailService mailService = new MailService(generalConfig);

		for (Object action : actions.getSendemailOrExecOrWaitstarted()) {

			if (action instanceof SendEmail) {

				SendEmail sendEmail = (SendEmail) action;

				String mailAddressTo = sendEmail.getTo();
				String mailSubject = sendEmail.getSubject();
				String content = sendEmail.getValue();

				mailService.send(mailAddressTo, mailSubject, content);

			} else if (action instanceof ExecuteCommand) {

				ExecuteCommand command = (ExecuteCommand) action;

				try {
					String cmd = command.getValue().trim();
					it.webrules.deploymanager.core.utils.System.execute(cmd);
				} catch (Exception e) {
					logger.error("Error executing command", e);
				}

			} else if (action instanceof Waitstarted) {

				logger.debug("Waiting start.");
				serverConnection.waitStart();

			} else if (action instanceof Waitdeployed) {

				try {
					logger.debug("Waiting deploy.");
					serverConnection.waitDeploy();
				} catch (Exception e) {
					logger.error("Error waiting deploy", e);
				}
			}

		}

	}
}
